# -*- coding: utf-8 -*-
import logging
import re

from commens import dump_to_json, get_back_data
from commens import reS, reMML



def print_res(tit,mml,line,index):
    if is_mml(mml):
        logCOMPARE.info('● %s\t%s\t%s\t[%d]'%(tit,line,mml,index))


def compare_re(title,sent,tag,*args):
    interMap = {}
    global intermediate
    lines = [x.strip() for x in re.split(r"[\n。]",sent)]
    for line in lines:
        if line == '':
            continue
        more = set(reMML.findall(line))
        less = []
        if more:
            for one in more:
                interMap[one] = line
            logCOMPARE.debug('-::- %s'%line)
            logCOMPARE.debug('more: ' + str(more))
            for i in range(len(reS)):
                m = reS[i].findall(line)
                for mm in m:
                    print_res(title, mm[0], line, i)
                    less.append(mm[0])
            logCOMPARE.debug('less: ' + str(less))
            if len(less) == 0:
                args[0].append('%s %d\n'%(line,0))
                for mml in set(more):
                    print_res(title, mml, line, -1)
            else:
                args[1].append('%s %d\n'%(line,1))
                for mml in list(set(more).difference(set(less))):
                    print_res(title, mml, line, -1)
    if interMap:
        if title in intermediate:
            intermediate[title][tag] = interMap
        else:
            intermediate[title] = {tag:interMap}







def is_mml(tag):
    return tag in data.keys()


def main():
    global data
    global intermediate
    data = get_back_data()
    negativeLines = []
    positiveLines = []
    for mml in data.keys():
        # print(mml)
        for section in data[mml].keys():
            # print(section)
            section_content = data[mml][section]
            type_section = type(section_content)
            if type_section is str:
                compare_re(mml,section_content,section,negativeLines,positiveLines)
            elif type_section is list:
                for param in section_content:
                    compare_re(mml,param['参数说明'],param['参数标识'],negativeLines,positiveLines)
    with open("negative.txt", 'w',encoding='utf-8') as f:
        print(len(negativeLines))
        f.writelines(negativeLines)
    with open("positive.txt", 'w',encoding='utf-8') as f:
        print(len(positiveLines))
        f.writelines(positiveLines)
    print('生成%d条中间信息'%len(intermediate))
    dump_to_json(intermediate,'INTERMI.json')
    print('Done')


if __name__ == '__main__':
    logCOMPARE = logging.getLogger("COMPARE")
    logCOMPARE.setLevel(logging.DEBUG)
    hdCOMPARE = logging.FileHandler("COMPARE.log", mode='w', encoding='utf-8')
    ch = logging.StreamHandler()
    ch.setLevel(logging.WARNING)
    hdCOMPARE.setLevel(logging.INFO)
    logCOMPARE.addHandler(hdCOMPARE)
    logCOMPARE.addHandler(ch)
    data = None
    intermediate = {}
    main()